package com.example.childpositionapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.GroundOverlayOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.example.childpositionapp.liveData.MyLiveData;
import com.example.childpositionapp.model.GetFence;
import com.example.childpositionapp.model.Location;
import com.example.childpositionapp.model.SocketSend;
import com.example.childpositionapp.network.BackService;
import com.example.childpositionapp.network.InitSocketThread;
import com.example.childpositionapp.network.Tool;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private MapView mMapView = null;
    BaiduMap mBaiduMap = null;
    LocationClient mLocationClient = null;
    BackService myService = null;
    Button bt;
    LatLng point1 = null;
    OverlayOptions option = null;
    PolygonOptions mPolygonOptions = null;
    TextView zhuangtai;
    boolean flag=true;
    boolean flag1=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermission();//申请权限
        //开启聊天服务
        ServiceConnection mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

                myService = ((BackService.MyBinder) service).getMyService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }

        };
        Intent myServiceIntent = new Intent(MainActivity.this, BackService.class);
        bindService(myServiceIntent, mServiceConnection,
                Context.BIND_AUTO_CREATE);

        zhuangtai=findViewById(R.id.zhuangtai);
        bt = findViewById(R.id.bt_add);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddFenceActivity.class);
                if (point1 != null) {
                    intent.putExtra("lon", point1.longitude);
                    intent.putExtra("lat", point1.latitude);
                } else {
                    intent.putExtra("lon", 0.0);
                    intent.putExtra("lat", 0.0);
                }
                startActivity(intent);
            }
        });
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
//        mBaiduMap.setMyLocationEnabled(true);
////定位初始化
//        try {
//            mLocationClient = new LocationClient(MainActivity.this);
//            //通过LocationClientOption设置LocationClient相关参数
//            LocationClientOption option = new LocationClientOption();
//            option.setOpenGps(true); // 打开gps
//            option.setCoorType("bd09ll"); // 设置坐标类型
//            option.setScanSpan(1000);
//
////设置locationClientOption
//            mLocationClient.setLocOption(option);
//
////注册LocationListener监听器
//            MyLocationListener myLocationListener = new MyLocationListener();
//            mLocationClient.registerLocationListener(myLocationListener);
////开启地图定位图层
//            mLocationClient.start();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////定义Maker坐标点
//        LatLng point1 = new LatLng(23.0414221667, 113.3888823333);
//        CoordinateConverter converter  = new CoordinateConverter()
//                .from(CoordinateConverter.CoordType.GPS)
//                .coord(point1);
//
////desLatLng 转换后的坐标
////        LatLng desLatLng = converter.convert();
//        LatLng point = converter.convert();
////构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.weizhi);
////构建MarkerOption，用于在地图上添加Marker
//        OverlayOptions option = new MarkerOptions()
//                .position(point)
//                .icon(bitmap);
////在地图上添加Marker，并显示
//        mBaiduMap.addOverlay(option);
//        MapStatus mMapStatus = new MapStatus.Builder().target(point).zoom(20).build();
//        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
//        mBaiduMap.setMapStatus(mapStatusUpdate);
        MyLiveData.getMessageData().observe(MainActivity.this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                Location location = new Gson().fromJson(s, Location.class);
                Log.d("坐标：", location.toString());
                if (location.getCode() == 202) {
                    isShowDialog();
                }
                else if (location.getCode() == 602) {
                   isShowDialog1();
                    flag1=false;

                }
                else if (location.getCode()==203){
                    zhuangtai.setText("在围栏内");
                    zhuangtai.setTextColor(0xAA00A600);
                    flag1=true;
                }
                LatLng point = new LatLng(location.getData().getY(), location.getData().getX());
//                 point1 = new LatLng(location.getData().getY(), location.getData().getX());
                CoordinateConverter converter = new CoordinateConverter()
                        .from(CoordinateConverter.CoordType.GPS)
                        .coord(point);

//desLatLng 转换后的坐标
//        LatLng desLatLng = converter.convert();
                if (location.getCode()==200){
                    point1 = converter.convert();
                    String send=new Gson().toJson(new SocketSend(point1.longitude,point1.latitude));
                    InitSocketThread.mWebSocket.send(send);
                    Log.d("INITSOCKET",send);
                    option = new MarkerOptions()
                            .position(point1)
                            .icon(bitmap);
                    mBaiduMap.clear();
                    mBaiduMap.addOverlay(option);
                    if (mPolygonOptions != null) {
                        mBaiduMap.addOverlay(mPolygonOptions);
                    }
                    MapStatus mMapStatus = new MapStatus.Builder().target(point1).build();
                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    mBaiduMap.setMapStatus(mapStatusUpdate);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        flag=true;
        flag1=true;
        zhuangtai=findViewById(R.id.zhuangtai);
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        Tool.getFence(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String text = response.body().string();
                Log.d("1111111111111111111111", text);
                GetFence fence = new Gson().fromJson(text, GetFence.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //定义Ground的显示地理范围
//                        LatLngBounds bounds = new LatLngBounds.Builder()
//                                .include(northeast)
//                                .include(southwest)
//                                .build();
                        if (fence.getCode() != 601&&fence.getCode()!=1001&&fence.getCode()!=1002) {
                            String xArr = fence.getData().getPolyX();
                            String yArr = fence.getData().getPolyY();
                            xArr = xArr.substring(1, xArr.length() - 1);
                            yArr = yArr.substring(1, yArr.length() - 1);

                            String[] numXArr = xArr.split(",");
                            String[] numYArr = yArr.split(",");

                            List<Double> xList = new ArrayList<>();
                            List<Double> yList = new ArrayList<>();
                            for (int i = 0; i < numXArr.length; i++) {
                                xList.add(Double.parseDouble(numXArr[i]));
                                yList.add(Double.parseDouble(numYArr[i]));
                            }
                            List<LatLng> points = new ArrayList<>();
                            for (int i = 0; i < xList.size(); i++) {
                                LatLng latLng = new LatLng(yList.get(i), xList.get(i));
                                points.add(latLng);
                            }
                            mPolygonOptions = new PolygonOptions()
                                    .points(points)
                                    .fillColor(0xAAff7575) //填充颜色
                                    .stroke(new Stroke(5, 0xAAff7575));//边框宽度和颜色


                            mBaiduMap.clear();
                            //在地图上显示多边形
                            mBaiduMap.addOverlay(mPolygonOptions);
                            if (option != null) {
                                mBaiduMap.addOverlay(option);
                            }
                        }else {
                            Toast.makeText(MainActivity.this,fence.getMessage(),Toast.LENGTH_SHORT);
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {

//            isPermissionRequested = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };

            for (String perm : permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    permissionsList.add(perm);
                    // 进入到这里代表没有权限.
                }
            }

            if (!permissionsList.isEmpty()) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
            }
        }
    }

    public void showDialog(String text) {
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setIcon(R.drawable.jingbao)//设置标题的图片
                    .setTitle(text)//设置对话框的标题
                    .setMessage(text)//设置对话框的内容
                    //设置对话框的按钮
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "点击了取消按钮", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "点击了确定的按钮", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    }).create();
            dialog.show();
    }

    public void isShowDialog(){
            showDialog("儿童报警");
            zhuangtai.setText("儿童报警");
            zhuangtai.setTextColor(0xAAFF0000);

    }
    public void isShowDialog1(){
        if (flag1){
            showDialog("在围栏外");
            zhuangtai.setText("离开围栏");
            zhuangtai.setTextColor(0xAAFF0000);
        }
    }
}